package com.allen.retrofit2_rxjava2.view.selectimageview.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;

import com.allen.retrofit2_rxjava2.app.MyApp;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.util.Log;

/**
 * 拍照、取图工具类
 *
 * @author GuiLin
 */
public class CameraUtil {

    private static String cameraDir = getSDCardPath() + "demo/Camera/";
    private static StringBuilder fileName = new StringBuilder();

    /**
     * 获取拍照的Intent
     *
     * @return
     */
    public static Intent getCameraIntent() {
        resetStringBuilder();
        fileName.append(getCurrentTime());
        fileName.append(".jpg");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        creatDir(cameraDir);
		/*intent.putExtra(MediaStore.EXTRA_OUTPUT,
				Uri.fromFile(new File(cameraDir, fileName.toString())));*/
        if (Build.VERSION.SDK_INT >= 24) {
            Uri contentUri = FileProvider.getUriForFile(MyApp.getContext(),
                    MyApp.getContext().getApplicationContext().getPackageName() + ".provider",
                    new File(cameraDir, fileName.toString()));
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    contentUri);
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                    Uri.fromFile(new File(cameraDir, fileName.toString())));
        }

        return intent;
    }

    /**
     * 获取拍照的Intent
     *
     * @return
     */
    public static Intent getCameraIntent(Context context) {
        resetStringBuilder();
        Uri pictureUri;
        fileName.append(getCurrentTime());
        fileName.append(".jpg");
        creatDir(cameraDir);
        Intent intent = null;

        if (Build.VERSION.SDK_INT >= 24) {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            ContentValues contentValues = new ContentValues(1);
            contentValues.put(MediaStore.Images.Media.DATA, new File(cameraDir, fileName.toString()).getAbsolutePath());
            pictureUri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    contentValues);
        } else {
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            pictureUri = Uri.fromFile(new File(cameraDir, fileName.toString()));
        }
        if (intent != null) {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri);
        }

        return intent;
    }

    /**
     * 获取相册intent
     *
     * @return
     */
    public static Intent getAlbumIntent() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setDataAndType(MediaStore.Images.Media.INTERNAL_CONTENT_URI,
                "image/*");
        return intent;
    }

    /**
     * 获取当前时间<br>
     */
    private static CharSequence getCurrentTime() {
        return DateFormat.format("yyyy-MM-dd-hh-mm-ss", new Date());
    }

    /**
     * 重置fileName
     */
    private static void resetStringBuilder() {
        if (fileName.length() > 0) {
            fileName.delete(0, fileName.length());
        }
    }

    /**
     * 获取图片真实路径
     */
    public static String getRealFilePath() {
        return cameraDir + fileName.toString();
    }

    /**
     * 创建文件夹
     */
    private static String creatDir(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        return dirPath;
    }

    /**
     * 获取文件地址
     *
     * @return
     */
    public static String getFilePath() {
        creatDir(cameraDir);
        File file = new File(cameraDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        return cameraDir;
    }

    /**
     * 判断SD卡是否可用
     */
    private static boolean sdCardIsExit() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取SD卡路径
     */
	public static String getSDCardPath() {
		if (sdCardIsExit()) {
			return Environment.getExternalStorageDirectory().toString() + "/";
		}
		return null;
	}
//    @SuppressLint("SdCardPath")
//    public static String getSDCardPath() {
//        String sdcard_path = null;
//        if (sdCardIsExit()) {
//            if (!TextUtils.isEmpty(Environment.getExternalStorageDirectory()
//                    .getAbsolutePath())) {
//                sdcard_path = Environment.getExternalStorageDirectory().getAbsolutePath();
//                return sdcard_path;
//            } else if (!TextUtils.isEmpty(Environment.getDataDirectory().toString())) {
//                sdcard_path = Environment.getDataDirectory().toString();
//                return sdcard_path;
//
//            } else {
//
//                String sd_default = Environment.getExternalStorageDirectory().getAbsolutePath();
//                if (sd_default.endsWith("/")) {
//                    sd_default = sd_default.substring(0, sd_default.length() - 1);
//                }
//                // 得到路径
//                try {
//                    Runtime runtime = Runtime.getRuntime();
//                    Process proc = runtime.exec("mount");
//                    InputStream is = proc.getInputStream();
//                    InputStreamReader isr = new InputStreamReader(is);
//                    String line;
//                    BufferedReader br = new BufferedReader(isr);
//                    while ((line = br.readLine()) != null) {
//                        if (line.contains("secure"))
//                            continue;
//                        if (line.contains("asec"))
//                            continue;
//                        if (line.contains("fat") && line.contains("/mnt/")) {
//                            String columns[] = line.split(" ");
//                            if (columns != null && columns.length > 1) {
//                                if (sd_default.trim().equals(columns[1].trim())) {
//                                    continue;
//                                }
//                                sdcard_path = columns[1];
//                            }
//                        } else if (line.contains("fuse") && line.contains("/mnt/")) {
//                            String columns[] = line.split(" ");
//                            if (columns != null && columns.length > 1) {
//                                if (sd_default.trim().equals(columns[1].trim())) {
//                                    continue;
//                                }
//                                sdcard_path = columns[1];
//                            }
//                        }
//                    }
//                    Log.d("sdcard_path", sdcard_path);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                    Log.d("获取sd卡路径异常", "SdCardPath");
//                }
//            }
//            return sdcard_path;
//        }
//        return null;
//    }
}
